package com.yape.webCrawler.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import com.yape.po.HsgtFundFlow;
import com.yape.webCrawler.base.BaseCrawler;
import com.yape.webCrawler.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Hazuki
 * @Date 2025/5/23 上午10:04
 * @Version 1.0
 */
@Slf4j
@Component("szhkConnect")
public class StockConnectCrawler extends BaseCrawler {
    private static final String API_URL = "https://push2.eastmoney.com/api/qt/kamt/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f56,f60,f61,f62,f63,f65,f66&ut=fa5fd1943c7b386f172d6893dbfba10b";

//    public StockConnectCrawler() {
//        super("szhkConnect");
//    }

    @Override
    public List<HsgtFundFlow> execute() throws IOException {
        String jsonpResponse = Jsoup.connect(getApiUrl())
                .ignoreContentType(true)
                .execute()
                .body();

        String jsonResponse = JsonUtils.extractJsonFromJsonp(jsonpResponse);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        JsonNode dataNode = rootNode.path("data");

        List<HsgtFundFlow> resultList = new ArrayList<>();

        // 沪股通数据 (Shanghai to HK)
        float sh2hkNetBuyAmt = (float) dataNode.path("sh2hk").path("netBuyAmt").asDouble();
        float sh2hkBuySellAmt = (float) dataNode.path("sh2hk").path("buySellAmt").asDouble();

        // 将沪股通数据添加到结果列表
        resultList.add(HsgtFundFlow.builder()
                .boardName("沪>港")
                .netBuyAmount(sh2hkNetBuyAmt)
                .totalTurnover(sh2hkBuySellAmt)
                .build());

        // 深股通数据 (Shenzhen to HK)
        float sz2hkNetBuyAmt = (float) dataNode.path("sz2hk").path("netBuyAmt").asDouble();
        float sz2hkBuySellAmt = (float) dataNode.path("sz2hk").path("buySellAmt").asDouble();

        // 将深股通数据添加到结果列表
        resultList.add(HsgtFundFlow.builder()
                .boardName("深>港")
                .netBuyAmount(sz2hkNetBuyAmt)
                .totalTurnover(sz2hkBuySellAmt)
                .build());

        //爬虫数据日志输出
        log.info("\n============爬虫数据表============");
        log.info(String.format("%-10s | %-12s | %-12s", "板块", "成交净买额", "成交总额"));
        log.info("--------------------------------------");
        log.info(String.format("%-10s | %-12.2f | %-12.2f", "沪>港", sh2hkNetBuyAmt, sh2hkBuySellAmt));
        log.info(String.format("%-10s | %-12.2f | %-12.2f", "深>港", sz2hkNetBuyAmt, sz2hkBuySellAmt));

//        context.complete(resultList.size());
        return resultList;
    }



    @Override
    protected String getApiUrl() {
        return API_URL;
    }
}